//
//  NoteDAO.swift
//  MyNotesDemo
//
//  Created by BZF on 2020/8/20.
//  Copyright © 2020 bzf. All rights reserved.
//

import Foundation

public class NoteDAO{
    private var dateFormatter = DateFormatter()
    
    //沙箱目录中的属性列表文件路径
    private var plistFilePath: String!
    
    public static let sharedInstance: NoteDAO = {
        let instance = NoteDAO()
        instance.plistFilePath = instance.applicationDocumentsDirectoryFile()
        instance.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        instance.createEditableCopyOfDatabaseIfNeeded()
        return instance
    }()
    
    //初始化属性列表文件
    private func createEditableCopyOfDatabaseIfNeeded(){
        let fileManager = FileManager.default
        
        //判断ocument目录下，NoteList.list文件存不存在
        let dbexits = fileManager.fileExists(atPath: self.plistFilePath)
        
        if(!dbexits){
            //框架资源对象，获得NoteDAO类所在的Bundle对象
            let frameworkBundle = Bundle(for: NoteDAO.self)
            let framePath = frameworkBundle.resourcePath as NSString?
            
            //给资源路径拼接文件名，获得文件的路径
            let defaultDBPath = framePath!.appendingPathComponent("NotesList.plist") as String
            
            do {
                try fileManager.copyItem(atPath: defaultDBPath, toPath: self.plistFilePath)
            } catch  {
                let nserror = error as NSError
                print("数据保存错误：",nserror.localizedDescription)
                assert(false,"错误写入文件")
            }
        }
    }
    
    private func applicationDocumentsDirectoryFile() -> String{
        
        //获取Document目录的位置,docmentDirectory只有一个元素的数组
        let documentDirectory: NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
        
        //获得Document目录下，NoteList.list文件的绝对路径
        let path = (documentDirectory[0] as AnyObject).appendingPathComponent("NoteList.list") as String
        
        return path
        
    }
    
    func insert(_ model: Note) -> Int{
        //读取属性列表文件内容
        let array = NSMutableArray(contentsOfFile: self.plistFilePath)
        let strDate = self.dateFormatter.string(from: model.date as Date)
        let dict = NSDictionary(objects: [strDate,model.content], forKeys: ["date" as NSCopying, "content" as NSCopying])
        array?.add(dict)
        array?.write(toFile: self.plistFilePath, atomically: true)
        return 0
    }
    
    func remove(_ mode: Note) -> Int{
        let array = NSMutableArray(contentsOfFile: self.plistFilePath)!
        for item in array{
            let dict = item as! NSDictionary
            let strDate = dict["date"] as! String
            let date = dateFormatter.date(from: strDate)
            
            //比较日期主键是否相等
            if date! == mode.date as Date{
                array.remove(dict)
                array.write(toFile: self.plistFilePath, atomically: true)
                break
            }
        }
        return 0
    }
    
    func modify(_ mode: Note) -> Int{
        let array = NSMutableArray(contentsOfFile: self.plistFilePath)!
        for item in array{
            let dict = item as! NSDictionary
            let strDate = dict["date"] as! String
            let date = dateFormatter.date(from: strDate)
            
            if date! == mode.date{
                array.remove(dict)
                array.write(toFile: self.plistFilePath, atomically: true)
                break
            }
        }
        return 0
    }
    
    func findAll() ->NSMutableArray{
        let array = NSMutableArray(contentsOfFile: self.plistFilePath)!
        
        let listData = NSMutableArray()
        
        for item in array{
            let dict = item as! NSDictionary
            
            let strDate = dict["date"] as! String
            let date = dateFormatter.date(from: strDate)!
            
            let content = dict["content"] as! String
            
            let note = Note(date: date, content: content)
            
            listData.add(note)
        }
        
        return listData
    }
    
    func findById(_ mode: Note) -> Note?{
        let array = NSMutableArray(contentsOfFile: self.plistFilePath)!
        
        for item in array{
            let dict = item as! NSDictionary
            
            let strDate = dict["date"] as! String
            let date = dateFormatter.date(from: strDate)
            
            let content = dict["content"] as! String
            
            if date! == mode.date as Date{
                let note = Note(date: date!, content: content)
                return note
            }
        }
        return nil
    }
}
